import {
  BrowserWindow,
  app,
  desktopCapturer,
  dialog,
  globalShortcut,
  ipcMain,
  nativeImage,
  nativeTheme,
  powerSaveBlocker,
  protocol,
  screen,
  session,
  shell,
} from 'electron';
import * as path from 'path';
import { usb } from 'usb';
import { isNotBlank } from 'web-plugin-utils';
import createProtocol from './createProtocol';
import { FindUsbKey, mSoftKey } from './usbkey';

import { Size, modalData } from '@/types';
import * as koffi from 'koffi';
import * as obsRecorder from './obsRecorder';

//禁止电脑进入睡眠
powerSaveBlocker.start('prevent-display-sleep');

// 禁用Https警告
app.commandLine.appendSwitch('ignore-certificate-errors');
// 允许音频自动播放
app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');

const isDevelopment = process.env.NODE_ENV === 'development';
const fs = require('fs');
const axios = require('axios');
const user32 = koffi.load('user32.dll');
koffi.alias('DWORD', 'uint32_t');
koffi.alias('HWND', koffi.pointer(koffi.opaque('HANDLE')));
koffi.proto('bool WNDENUMPROC(HWND hwnd,uint lParam)');
const ShowWindow = user32.func(
  'bool __stdcall ShowWindow(HWND hWnd, int nCmdShow)',
);
const FindWindowExW = user32.func(
  'HWND __stdcall FindWindowExW(HWND hWndParent, HWND hWndChildAfter, const char16_t *lpszClass, const char16_t *lpszWindow)',
);

let mainWindow: BrowserWindow | undefined;
let meetWindow: BrowserWindow | undefined;
let chatWindow: BrowserWindow | undefined;
let videoWindow: BrowserWindow | undefined;
let loginWindow: BrowserWindow | undefined;
let ObsWindow: BrowserWindow | undefined;
let inviteUserWindow: BrowserWindow | undefined;
let shareOperationBarWindow: BrowserWindow | undefined;
let whiteboardWindow: BrowserWindow | undefined;
let meetingRemindWindow: BrowserWindow | undefined;
let meetingShareRecordRemindWindow: BrowserWindow | undefined;

let ObsModalWindow: BrowserWindow | undefined;
const { WebSocket, WebSocketServer } = require('ws');
let wss = new WebSocketServer({ port: 8899 });
let webSocketClient: WebSocket | null = null;
wss.on('connection', (ws) => {
  console.log('Client connected');
  // 监听客户端发送的消息
  ws.on('message', (message) => {
    console.log(`Received: ${message}`);
  });
  // 向客户端发送消息
  ws.send(JSON.stringify({ message: "'Hello, client!'" }));
});
// app.disableHardwareAcceleration();

let selectedId = '';
let whiteboardIgnore = false;
let shareIgnore = false;

const sendWsMessage = (sendMsg: any) => {
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(JSON.stringify(sendMsg));
    }
  });
};

ipcMain.handle('recording-start', (event) => {
  obsRecorder.start(ObsWindow);
  return { recording: true };
});

ipcMain.handle('recording-stop', (event) => {
  obsRecorder.stop();
  return { recording: false };
});

ipcMain.handle('setLiving', (event, data: boolean) => {
  console.log('setLiving', data);
  mainWindow?.webContents.send('setLiving', data);
  return true;
});

ipcMain.handle('updatePatientActive', (event, data: any) => {
  console.log('updatePatientActive', data);
  // ObsModalWindow?.hide()
  mainWindow?.webContents.send('updatePatientActive', data);
  return true;
});
ipcMain.handle('getSourceOption', (event, data: string) => {
  return obsRecorder.getSourceOption(data);
});
// 获取所有的窗口
ipcMain.handle('getAllWindows', (event, data: any) => {
  console.log('getAllWindow', data);
  return obsRecorder.getAllWindow();
});
// 设置
ipcMain.handle(
  'setSetting',
  (event, data: { category: any; parameter: any; value: any }) => {
    console.log('getAllWindow', data);
    const { category, parameter, value } = data;
    obsRecorder.setSetting(category, parameter, value);
    obsRecorder.saveObsSettingToFile();
    return;
  },
);

ipcMain.handle('getTeachConfig', (event) => {
  return obsRecorder.getTeachConfig();
});
ipcMain.handle('setTeachConfig', (event, data: any) => {
  console.log('setTeachConfig', data);
  return obsRecorder.setTeachConfig(data);
});

ipcMain.handle('createObsModal', async (e) => {
  // await createObsModalWindow();
  return true;
});

//窗体发送事件
ipcMain.handle(
  'sendWindowEvent',
  async (
    e,
    { name, event, data }: { name: string; event: string; data: any },
  ) => {
    // await createObsModalWindow();
    let window = undefined;

    if (name === 'mainWindow') {
      window = mainWindow;
    } else if (name === 'loginWindow') {
      window = loginWindow;
    } else {
      return;
    }
    window!.webContents.send(event, data);
    return true;
  },
);
type windowSizeType = 'mini' | 'normal' | 'large';
const windowSize: {
  [key in windowSizeType]: Size;
} = {
  mini: {
    width: 500,
    height: 280,
  },
  normal: {
    width: 990,
    height: 870,
  },
  large: {
    width: 1280,
    height: 820,
  },
};
ipcMain.handle(
  'showObsModal',
  async (event, data: modalData, option?: windowSizeType | Size) => {
    if (hasChildDisplay) {
      console.log('正在关闭中。。。');
      return;
    }
    let options: Size;
    if (!option) {
      options = windowSize['normal'];
    } else if (typeof option === 'string') {
      options = windowSize[option as windowSizeType];
    } else if (
      typeof option === 'object' &&
      'width' in option &&
      'height' in option
    ) {
      // 这是 Size 类型
      options = option as Size;
    } else {
      console.log('option类型错误', option);
      options = windowSize['normal'];
    }
    data.showClose = data.showClose ?? true;
    ObsModalWindow?.setSize(options.width, options.height);
    const { width, height } = screen.getPrimaryDisplay().workAreaSize; // 获取屏幕的尺寸信息
    const position = {
      x: Math.floor((width - options.width) / 2), // 计算窗口的水平位置
      y: Math.floor((height - options.height) / 2), // 计算窗口的垂直位置
    };
    ObsModalWindow?.setPosition(position.x, position.y);
    ObsModalWindow!.webContents.send('initModal', data);
    ObsModalWindow!.show();
  },
);

app.on('will-quit', obsRecorder.shutdown);
//窗口是否有画布
let hasChildDisplay = false;
//是否关闭Modal   isCloseModal
let isCloseModal = false;

async function createObsModalWindow() {
  if (!ObsModalWindow) {
    ObsModalWindow = new BrowserWindow({
      modal: true,
      parent: mainWindow,
      width: 990,
      height: 870,
      frame: false,
      autoHideMenuBar: true,
      useContentSize: true,
      skipTaskbar: true,
      show: false,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
      },
    });

    if (isDevelopment) {
      await ObsModalWindow.loadURL('http://localhost:8888/#/obs/modal');
    } else {
      await ObsModalWindow.loadURL('app://./index.html/#/obs/modal');
    }
    ObsModalWindow.on('closed', async (e) => {
      const closePreview = () => {
        return new Promise((resolve) => {
          setTimeout(() => {
            if (hasChildDisplay) {
              obsRecorder.closePreviewChild('ObsModalWindow');
              hasChildDisplay = false;
            }
            if (!isCloseModal) {
              ObsModalWindow = undefined;
              createObsModalWindow().then(() => {
                resolve();
              });
            }
          }, 100);
        });
      };
      await closePreview();
    });
    ObsModalWindow.on('close', (e) => {
      if (hasChildDisplay || isCloseModal) {
        return true;
      } else {
        e.preventDefault();
        ObsModalWindow?.hide();
      }
    });

    ObsModalWindow.webContents.ipc.handle('closeObsModal', async (event) => {
      console.error('关闭窗口', event);
      ObsModalWindow!.close();
    });

    // 添加场景
    ObsModalWindow.webContents.ipc.handle(
      'createScene',
      (event, sceneName: string) => {
        const result = obsRecorder.createScene(sceneName);
        sendWsMessage({ type: 'initData' });
        obsRecorder.saveObsSettingToFile();

        return result;
      },
    );

    ObsModalWindow.webContents.ipc.handle(
      'createModalSource',
      (event, sourceParam: { sceneName: string; id: string; name: string }) => {
        const result = obsRecorder.createSource(sourceParam);
        sendWsMessage({ type: 'initData' });
        obsRecorder.saveObsSettingToFile();

        return result;
      },
    );

    // 修改源设置
    ObsModalWindow.webContents.ipc.handle(
      'updateSourceSettings',
      (
        event,
        updateConfig: {
          sceneName: string;
          name: string;
          updateSettings: { [name: string]: any };
        },
      ) => {
        console.log('updateSourceSettings', updateConfig);
        const result = obsRecorder.updateSourceSettings(updateConfig);
        obsRecorder.selectSource(updateConfig.sceneName, updateConfig.name);
        obsRecorder.saveObsSettingToFile();

        return result;
      },
    );

    //获取所有显示器
    ObsModalWindow.webContents.ipc.handle('getAllDisplays', () => {
      console.error(screen.getAllDisplays());
      return screen.getAllDisplays();
      // return  screen.getAllDisplays()
      // event.returnValue = obsRecorder.getAllDisplays();
    });

    // 显示器设置
    ObsModalWindow.webContents.ipc.handle('selectDisPlay', (event, bounds) => {
      const result = obsRecorder.selectDisPlay(bounds);
      obsRecorder.saveObsSettingToFile();

      return result;
    });

    // 修改SourceItem设置
    ObsModalWindow.webContents.ipc.handle(
      'updateSceneItemSettings',
      (
        event,
        updateConfig: {
          sceneName: string;
          name: string;
          updateSettings: { [name: 'visible' | 'position']: any };
        },
      ) => {
        console.log('updateConfig', updateConfig);
        const result = obsRecorder.updateSceneItemSettings(updateConfig);
        obsRecorder.saveObsSettingToFile();

        return result;
      },
    );

    // 获取源配置
    ObsModalWindow.webContents.ipc.handle(
      'getSourceSettings',
      (event, sourceParam: { sceneName: string; name: string }) => {
        return obsRecorder.getSourceSettings(sourceParam);
      },
    );

    // 获取摄像头
    ObsModalWindow.webContents.ipc.handle('getALlCameras', (event) => {
      return obsRecorder.getALlCameras();
    });

    //获取所有设置
    ObsModalWindow.webContents.ipc.handle(
      'getAllSetting',
      (event, cate: string[]) => {
        const result = obsRecorder.getAllSetting(cate);
        return result;
      },
    );

    //设置用户配置
    ObsModalWindow.webContents.ipc.handle(
      'setUserSetting',
      (event, cate: any) => {
        const result = obsRecorder.setUserSetting(cate);
        obsRecorder.saveObsSettingToFile();
        return result;
      },
    );
    //设置用户配置
    ObsModalWindow.webContents.ipc.handle(
      'preview-bounds-child',
      (event, bounds) => {
        return obsRecorder.resizePreviewChild(
          ObsModalWindow,
          bounds,
          'ObsModalWindow',
        );
      },
    );
    ObsModalWindow.webContents.ipc.handle(
      'preview-init-child',
      (event, bounds) => {
        hasChildDisplay = true;
        const result = obsRecorder.setupPreviewChild(
          ObsModalWindow,
          bounds,
          'ObsModalWindow',
        );
        return result;
      },
    );

    //获取所有设置
    ObsModalWindow.webContents.ipc.handle(
      'getDirection',
      (event, cate: string[]) => {
        return new Promise((resolve) => {
          // 打开选择目录对话框
          dialog
            .showOpenDialog(ObsModalWindow!, {
              properties: ['openDirectory'],
            })
            .then((result) => {
              if (!result.canceled && result.filePaths.length > 0) {
                const selectedDirectory = result.filePaths[0];
                console.log('选择的目录地址：', selectedDirectory);
                resolve(selectedDirectory);
                // 在这里处理获取到的目录地址
              }
            });
        });
      },
    );

    //获取所有设置
    ObsModalWindow.webContents.ipc.handle(
      'saveImg',
      (event, filePath: string) => {
        if (fs.existsSync(filePath)) {
          return obsRecorder.saveImg(filePath);
        }
        return '';
      },
    );
  }
}

protocol.registerSchemesAsPrivileged([
  {
    scheme: 'app',
    privileges: {
      secure: true,
      standard: true,
      supportFetchAPI: true,
    },
  },
]);

const InitObsEvent = async (win: BrowserWindow) => {
  // if (isDevelopment) {
  //   await win.loadURL('http://localhost:8888/#/obs');
  //   // await ObsModalWindow.loadURL('http://localhost:8888/#/obs/modal');
  // } else {
  //   await win.loadURL('app://./index.html/#/obs');
  //   // await ObsModalWindow.loadURL('app://./index.html/#/obs/modal');
  // }

  // 源选中
  win.webContents.ipc.handle('test', (event, data: any) => {
    console.log('test', data);
    // const result = obsRecorder.setupAudio(data)

    return obsRecorder.test(data);
  });

  win.webContents.ipc.on('changeLocation', (event, data: { name: string }) => {
    console.log('changeLocation', data);
    const result = obsRecorder.changeLocation(data);
    return result;
  });
  win.webContents.ipc.handle(
    'proxyObs',
    (event, data: { method: string; name: string; sourceMethod: string }) => {
      console.log('proxyObs', data);
      const result = obsRecorder[data.method](data);
      return result;
    },
  );
  win.webContents.ipc.handle(
    'setupAudio',
    (event, data: { name: string; value: number }) => {
      console.log('setupAudio', data);
      const result = obsRecorder.setupAudio(data);
      obsRecorder.saveObsSettingToFile();
      return result;
    },
  );
  win.webContents.ipc.handle('getAudio', (event, data: any) => {
    const result = obsRecorder.getAudio();

    return result;
  });

  win.webContents.ipc.handle(
    'exChangeSort',
    (
      event,
      data: {
        type: 'scene' | 'source';
        step: number;
      },
    ) => {
      const result = obsRecorder.exChangeSort(data);
      obsRecorder.saveObsSettingToFile();
      return result;
    },
  );

  win.webContents.ipc.handle('performanceStatistics', (event) => {
    const result = obsRecorder.performanceStatistics();
    return result;
  });

  win.webContents.ipc.handle(
    'updateTransition',
    (event, transType: string, timer: number) => {
      const result = obsRecorder.updateTransition(transType, timer);
      console.log('updateTransition', result);
      obsRecorder.saveObsSettingToFile();
      return result;
    },
  );

  win.webContents.ipc.handle('getSaveData', (event) => {
    const result = obsRecorder.getSaveData();
    console.log('getSaveData', result);
    return result;
  });

  win.webContents.ipc.handle(
    'changeScene',
    async (event, sceneName, sourceName: string) => {
      obsRecorder.changeScene(sceneName, sourceName);
      obsRecorder.saveObsSettingToFile();
      // obsRecorder.setSelected({selectScene: sceneName});
      return true;
    },
  );
  win.webContents.ipc.handle('recording-init', async (event) => {
    console.error('recording-init');
    // obsRecorder.initOBSMul();
    obsRecorder.initialize(win);
    console.error('recording-init  end');
    return true;
  });
  win.webContents.ipc.handle('preview-init', (event, bounds) => {
    const result = obsRecorder.setupPreview(win, bounds);
    return result;
  });
  win.webContents.ipc.handle('getObsCanvasSize', (event, bounds) => {
    const result = obsRecorder.getObsCanvasSize();
    return result;
  });
  win.webContents.ipc.handle('preview-bounds', (event, bounds) => {
    return obsRecorder.resizePreview(win, bounds);
  });
  win.webContents.ipc.handle('update-rtmp', (event, bounds) => {
    return obsRecorder.udpateRtmp(win, bounds);
  });
  // 开始直播/结束直播
  win.webContents.ipc.handle('toggleStreaming', (event, bounds) => {
    return obsRecorder.toggleStreaming(bounds);
  });
  // 显示器设置
  win.webContents.ipc.handle('selectDisPlay', (event, bounds) => {
    return obsRecorder.selectDisPlay(bounds);
  });
  win.webContents.ipc.handle(
    'createSource',
    (event, sourceParam: { sceneName: string; id: string; name: string }) => {
      console.log('main');
      const result = obsRecorder.createSource(sourceParam);
      sendWsMessage({ type: 'initData' });
      obsRecorder.saveObsSettingToFile();

      return result;
    },
  );

  // 修改SourceItem设置
  win.webContents.ipc.handle(
    'updateSceneItemSettings',
    (
      event,
      updateConfig: {
        sceneName: string;
        name: string;
        updateSettings: { [name: 'visible' | 'position']: any };
      },
    ) => {
      console.log('updateConfig', updateConfig);
      const result = obsRecorder.updateSceneItemSettings(updateConfig);
      obsRecorder.saveObsSettingToFile();

      return result;
    },
  );

  // 修改源设置
  win.webContents.ipc.handle(
    'updateSourceSettings',
    (
      event,
      updateConfig: {
        sceneName: string;
        name: string;
        updateSettings: { [name: string]: any };
      },
    ) => {
      console.log('updateConfig', updateConfig);
      const result = obsRecorder.updateSourceSettings(updateConfig);
      obsRecorder.saveObsSettingToFile();

      return result;
    },
  );
  // 添加场景
  win.webContents.ipc.handle('createScene', (event, sceneName: string) => {
    if (obsRecorder.getSceneModels().getScene(sceneName) === null) {
      dialog.showMessageBoxSync(win, {
        message: `场景 ${sceneName}已存在`,
        type: 'warning',
        buttons: ['取消', '确定'],
        title: '可视化综合培训',
      });
      return;
    }
    const result = obsRecorder.createScene(sceneName);
    sendWsMessage({ type: 'initData' });
    obsRecorder.saveObsSettingToFile();

    return result;
  });
  // 删除场景
  win.webContents.ipc.handle('removeScene', (event, sceneName: string) => {
    const image = nativeImage.createFromPath('favicon.ico');
    const messageResult = dialog.showMessageBoxSync(win, {
      message: `是否确定移除 ${sceneName}?`,
      type: 'warning',
      buttons: ['取消', '确定'],
      icon: image,
      title: '可视化综合培训',
    });
    if (messageResult === 1) {
      const length = obsRecorder.getSceneModels().get().length;
      if (length < 2) return;
      const result = obsRecorder.removeScene(sceneName);
      sendWsMessage({ type: 'initData' });
      obsRecorder.saveObsSettingToFile();

      return result;
    }
  });
  // 删除源
  win.webContents.ipc.handle(
    'removeSource',
    (event, sourceParam: { sceneName: string; name: string }) => {
      const image = nativeImage.createFromPath('favicon.ico');
      const source = obsRecorder
        .getSceneModels()
        .getSource(sourceParam.sceneName, sourceParam.name);
      const messageResult = dialog.showMessageBoxSync(win, {
        message: `是否确定移除 ${source?.aliasName}?`,
        type: 'warning',
        buttons: ['取消', '确定'],
        icon: image,
        title: '可视化综合培训',
      });
      if (messageResult === 1) {
        const result = obsRecorder.removeSource(sourceParam);
        sendWsMessage({ type: 'initData' });
        obsRecorder.saveObsSettingToFile();
        return result;
      }
    },
  );
  // 获取源配置
  win.webContents.ipc.handle(
    'getSourceSettings',
    (event, sourceParam: { sceneName: string; name: string }) => {
      return obsRecorder.getSourceSettings(sourceParam);
    },
  );
  // ipcMain.on('obsSourceInit', (event, data) => {
  //     win.webContents.send('obsSourceInit', data)
  // })
  win.webContents.ipc.handle('getAllScene', (event) => {
    const all = obsRecorder.getAllScene();
    console.log('all', all);
    return all;
  });
  win.webContents.ipc.handle('getOsnSelect', (event) => {
    const result = obsRecorder.getOsnSelect();
    console.log('getOsnSelect', result);
    return result;
  });
  // win.webContents.ipc.handle('setSelected', (event,selectData:{
  //     selectSource: string,
  //     selectScene: string
  // }) => {
  //     obsRecorder.setSelected(selectData);
  //     return true
  // });

  win.webContents.ipc.handle('getAllSource', (event, name) => {
    return obsRecorder.getAllSource(name);
  });
  win.webContents.ipc.handle('getALlCameras', (event) => {
    return obsRecorder.getALlCameras();
  });

  win.webContents.ipc.handle('getSetting', (event, bounds) => {
    return obsRecorder.getSetting(bounds);
  });
  win.on('resize', () => {
    console.log('win resize');
    win.webContents.send('resizePreview');
  });

  win.webContents.ipc.handle('getAllDisplays', () => {
    console.error(screen.getAllDisplays());
    return screen.getAllDisplays();
    // return  screen.getAllDisplays()
    // event.returnValue = obsRecorder.getAllDisplays();
  });

  // 鼠标移动
  win.webContents.ipc.handle(
    'mouseMovePosition',
    (
      event,
      senceSelect: string,
      sourceSelect: string,
      clientX: number,
      clientY: number,
      scaleFactor: number,
    ) => {
      return obsRecorder.mouseMove(
        senceSelect,
        sourceSelect,
        clientX,
        clientY,
        scaleFactor,
      );
    },
  );

  // 源选中
  win.webContents.ipc.handle(
    'selectSource',
    (event, senceSelect: string, sourceSelect: string) => {
      obsRecorder.setSelected({ selectSource: sourceSelect });
      return obsRecorder.selectSource(senceSelect, sourceSelect);
    },
  );
  // 获取源详情
  win.webContents.ipc.on('sourceDetailMessage', (event, bounds) => {
    event.returnValue = obsRecorder.sourceDetailMessage(bounds);
    return event.returnValue;
  });
  // 计算坐标偏移
  win.webContents.ipc.handle(
    'coordinateDifference',
    (
      event,
      senceSelect: string,
      sourceSelect: string,
      clientX: number,
      clientY: number,
      leftMargin: number,
      scale: number,
    ) => {
      return obsRecorder.coordinateDifference(
        senceSelect,
        sourceSelect,
        clientX,
        clientY,
        leftMargin,
        scale,
      );
    },
  );
  win.webContents.ipc.handle(
    'uploadVideo',
    (event, peerServer: string, authorization: string) => {
      // 读取目录中的文件和子目录
      const selectedFilePath = '/videos/2023-10-19 14-20-48.mp4';
      // 读取 video 文件为二进制数据
      const fileData = fs.readFileSync(process.cwd() + selectedFilePath);
      // 发送文件数据到后端
      axios
        .post(peerServer + `/api/peerUser/uploadVideo`, fileData, {
          headers: {
            'Content-Type': 'video/mp4', // 根据文件类型设置正确的内容类型
            authorization: authorization,
          },
        })
        .then((response: { data: any }) => {
          console.log('上传成功', response.data);
        })
        .catch((error: any) => {
          console.error('上传失败', error);
        });
    },
  );

  win.webContents.ipc.handle('shutdownOBS', (event, route: any) => {
    if (route && route.path) {
      obsRecorder.shutdown();
    }
  });
  // Open the DevTools.
  // win.webContents.openDevTools();
};

async function createMainWindow(
  role: string = '',
  username: string = '',
  nickname: string = '',
  id: string = '',
) {
  if (mainWindow === undefined) {
    const { workArea, workAreaSize } = screen.getPrimaryDisplay();
    mainWindow = new BrowserWindow({
      minWidth: 1400,
      minHeight: 860,
      maxWidth: workArea.width,
      maxHeight: workArea.height,
      width: 1400,
      height: 860,
      frame: false,
      useContentSize: true,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    // mainWindow.setAspectRatio(Math.floor(workArea.width / workArea.height));

    mainWindow.on('closed', () => {
      mainWindow = undefined;
      obsRecorder.shutdown();
      console.log('mainWindowClosed', ObsModalWindow?.isDestroyed());
      ObsModalWindow?.destroy();
    });

    // console.log(ObsModalWindow)
    if (ObsModalWindow === undefined || ObsModalWindow.isDestroyed()) {
      ObsModalWindow = undefined;
      isCloseModal = false;
      await createObsModalWindow();
    }

    mainWindow.setMenu(null);
    if (isNotBlank(username)) {
      if (isDevelopment) {
        await mainWindow.loadURL(
          `http://localhost:8888?role=${role}&username=${username}&nickname=${nickname}&id=${id}`,
        );
      } else {
        await mainWindow.loadURL(
          `app://./index.html?role=${role}&username=${username}&nickname=${nickname}&id=${id}`,
        );
      }
      mainWindow.maximize();
    }
    // mainWindow.webContents.openDevTools();
    mainWindow.webContents.ipc.on('toMin', () => {
      mainWindow?.minimize();
    });
    mainWindow.webContents.ipc.on('toMax', () => {
      if (mainWindow?.isMaximized()) {
        mainWindow.unmaximize();
      } else {
        mainWindow?.maximize();
      }
    });
    mainWindow.webContents.ipc.on('toClose', () => {
      if (webSocketClient) {
        webSocketClient.close();
      }
      meetWindow?.close();
      videoWindow?.close();
      ObsWindow?.close();
      inviteUserWindow?.close();
      isCloseModal = true;
      mainWindow?.close();
    });
    mainWindow.webContents.ipc.on('openLogin', () => {
      if (webSocketClient) {
        webSocketClient.close();
      }
      createLoginWindow();
    });

    mainWindow?.webContents.ipc.on(
      'send-websocket-message',
      (event, message) => {
        if (webSocketClient) {
          webSocketClient.send(message);
          console.log('已发送WebSocket消息:', message);
        }
      },
    );

    await InitObsEvent(mainWindow);
  }
  mainWindow!.on('move', () => {
    shareOperationBarWindow?.setIgnoreMouseEvents(false);
    whiteboardWindow?.setIgnoreMouseEvents(false);
  });

  mainWindow!.on('moved', () => {
    if (shareIgnore) {
      shareOperationBarWindow?.setIgnoreMouseEvents(true, {
        forward: true,
      });
    }
    if (whiteboardIgnore) {
      whiteboardWindow?.setIgnoreMouseEvents(true, {
        forward: true,
      });
    }
  });

  mainWindow!.webContents.ipc.handle('getMainWindowSize', (event: any) => {
    const { x, y, width, height } = mainWindow!.getContentBounds();
    return { x, y, width, height };
  });
}

async function createLoginWindow() {
  if (loginWindow == null) {
    loginWindow = new BrowserWindow({
      width: 500,
      height: 340,
      frame: false,
      resizable: false,
      useContentSize: true,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    loginWindow.on('closed', () => {
      loginWindow = undefined;
    });
    loginWindow.setMenu(null);
    if (isDevelopment) {
      // loginWindow.webContents.openDevTools();
      await loginWindow.loadURL('http://localhost:8888/#/login');
    } else {
      await loginWindow.loadURL('app://./index.html/#/login');
    }
    loginWindow.webContents.ipc.on('toMin', () => {
      loginWindow?.minimize();
    });
    loginWindow.webContents.ipc.on('toMax', () => {
      if (loginWindow?.isMaximized()) {
        loginWindow.unmaximize();
      } else {
        loginWindow?.maximize();
      }
    });
    loginWindow.webContents.ipc.on('toClose', () => {
      loginWindow?.close();
    });
    loginWindow.webContents.ipc.on(
      'openMainWindow',
      (_, role, username, nickname, avatar, id, blackWhiteStatus, serverIp) => {
        createMainWindow(role, username, nickname, id);

        const message = {
          messageType: 'login',
          userId: id,
          userName: username,
          avatar: avatar,
          blackWhiteStatus: blackWhiteStatus,
        };
        initWebSocket(serverIp, message);
        loginWindow?.close();
      },
    );
    loginWindow.webContents.ipc.on('openSettingsWindow', async () => {
      await createMainWindow();
      if (isDevelopment) {
        await mainWindow?.loadURL(`http://localhost:8888/#/settings`);
      } else {
        await mainWindow?.loadURL(`app://./index.html/#/settings`);
      }
      loginWindow?.close();
    });
  }
}

let lastAbort: AbortController;

function checkUsbKey() {
  if (isDevelopment) {
    return;
  }
  const flag = FindUsbKey();
  if (!flag) {
    if (lastAbort == undefined || lastAbort?.signal.aborted) {
      lastAbort = new AbortController();
      dialog
        .showMessageBox(loginWindow ?? mainWindow!, {
          title: '加密狗',
          type: 'error',
          message: '未检测到加密狗',
          buttons: ['退出'],
          noLink: true,
          signal: lastAbort.signal,
        })
        .then(({ response }) => {
          if (response === 0 && !lastAbort.signal.aborted) {
            app.quit();
          }
        });
    }
  } else {
    lastAbort?.abort();
  }
}

app.on('ready', async () => {
  nativeTheme.themeSource = 'dark';
  createProtocol('app');
  // await createObsWindow();
  // await createObsModalWindow();
  await createLoginWindow();
  // checkUsbKey();
  usb.on('attach', ({ deviceDescriptor }) => {
    if (
      mSoftKey.MacthUKeyID({
        vendorId: deviceDescriptor.idVendor,
        productId: deviceDescriptor.idProduct,
      })
    ) {
      console.log('收到有加密锁初插入的消息');
      checkUsbKey();
    }
  });

  usb.on('detach', ({ deviceDescriptor }) => {
    if (
      mSoftKey.MacthUKeyID({
        vendorId: deviceDescriptor.idVendor,
        productId: deviceDescriptor.idProduct,
      })
    ) {
      console.log('收到有加密锁被拨出的消息');
      checkUsbKey();
    }
  });

  //权限放行
  session.defaultSession.setPermissionRequestHandler(
    (webContents, permission, callback, details) => {
      callback(true);
    },
  );

  //Media权限放行
  session.defaultSession.setDisplayMediaRequestHandler((request, callback) => {
    desktopCapturer
      .getSources({ types: ['window', 'screen'] })
      .then((sources) => {
        // Grant access to the first screen found.
        const selectedSource = sources.find(
          (source) => source.id === selectedId,
        );
        if (selectedSource) {
          callback({ video: { id: selectedId, name: '' } });

          const selectedWindow = FindWindowExW(0, 0, null, selectedSource.name);
          ShowWindow(selectedWindow, 1); //正常显示窗口
          ShowWindow(selectedWindow, 3); //最大化窗口
        } else {
          callback({ video: sources[0] });
        }
      });
  });

  globalShortcut.register('ALT+T', () => {
    BrowserWindow.getAllWindows().forEach((w) => {
      if (w.webContents.isDevToolsOpened()) {
        w.webContents.closeDevTools();
      } else {
        w.webContents.openDevTools();
      }
    });
  });

  globalShortcut.register('ctrl+shift+q', async () => {
    const cur = BrowserWindow.getFocusedWindow();
    if (cur) {
      cur.webContents.openDevTools();
    }
  });

  globalShortcut.register('ALT+R', () => {
    BrowserWindow.getAllWindows().forEach((w) => {
      w.reload();
    });
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (mainWindow === null) {
    createLoginWindow();
  }
});

ipcMain.on('openMeet', (_, type, meetingCode, meetingName) => {
  if (meetWindow == null) {
    meetWindow = new BrowserWindow({
      minWidth: 1200,
      minHeight: 765,
      width: 1200,
      height: 765,
      useContentSize: true,
      frame: false,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
      },
    });
    mainWindow?.webContents.send('setLiving', true);
    meetWindow.on('closed', () => {
      meetWindow = undefined;
    });
  }

  meetWindow.setMenu(null);
  meetWindow.webContents.openDevTools();
  if (isDevelopment) {
    meetWindow.loadURL(
      'http://localhost:8888/#/meet?streamTypeTmp=' +
        type +
        '&meetingCode=' +
        meetingCode +
        '&meetingName=' +
        meetingName,
    );
  } else {
    meetWindow.loadURL(
      'app://./index.html/#/meet?streamTypeTmp=' +
        type +
        '&meetingCode=' +
        meetingCode +
        '&meetingName=' +
        meetingName,
    );
  }
  if (inviteUserWindow != undefined) {
    inviteUserWindow.close();
    inviteUserWindow = undefined;
  }
  meetWindow.webContents.ipc.handle('desktop-sources', async (event) => {
    // 获取可捕获的资源，包括桌面
    const sources = await desktopCapturer.getSources({
      types: ['window', 'screen'],
    });
    const windows = BrowserWindow.getAllWindows();
    const targetWindow = windows[0]; // 假设这里获取第一个窗口，您可以根据需要选择不同的窗口
    const targetWebContents = targetWindow.webContents;
    console.log('targetWebContents:', targetWebContents.id);
    let reslutList = [];
    for (const source of sources) {
      const image = nativeImage.createFromDataURL(source.thumbnail.toDataURL());
      const reslut = {
        imageUrl: image.toDataURL(),
        name: source.name,
        displayId: source.id,
      };
      reslutList.push(reslut);
    }
    return reslutList;
  });

  //获取选中sourceId
  meetWindow.webContents.ipc.handle(
    'desktop-selectedSource',
    async (event, newSelectedId: string) => {
      selectedId = newSelectedId;
    },
  );

  //在窗口关闭时触发的事件
  meetWindow.on('closed', (event: any) => {
    console.log('------------我是关闭事件');
  });

  meetWindow.webContents.ipc.handle(
    'chat-show',
    async (event, showFlag: boolean) => {
      const { width, height } = meetWindow!.getBounds();
      if (showFlag) {
        meetWindow?.setSize(width + width / 4, height);
      } else {
        meetWindow?.setSize(width * 0.8, height);
      }
    },
  );

  meetWindow.webContents.ipc.on('toMeetingMin', () => {
    meetWindow?.minimize();
  });
  meetWindow.webContents.ipc.on('toMeetingMax', () => {
    if (meetWindow?.isMaximized()) {
      meetWindow.unmaximize();
    } else {
      meetWindow?.maximize();
    }
  });
  meetWindow?.webContents.ipc.on('send-websocket-message', (event, message) => {
    if (webSocketClient) {
      webSocketClient.send(message);
      console.log('已发送WebSocket消息:', message);
    }
  });
  meetWindow?.webContents.ipc.on(
    'open-shareOperationBar',
    async (
      event,
      volumeList: [],
      cameraList: [],
      volumeFlag: boolean,
      cameraFlag: boolean,
      meetingCode: string,
    ) => {
      await createShareOperationBarWindow(
        volumeList,
        cameraList,
        volumeFlag,
        cameraFlag,
        meetingCode,
      );
      meetWindow!.minimize();
    },
  );
  meetWindow.webContents.ipc.on('toMeetingClose', () => {
    meetWindow?.close();
    whiteboardWindow?.close();
    whiteboardWindow = undefined;
    shareOperationBarWindow?.close();
    shareOperationBarWindow = undefined;
    meetingShareRecordRemindWindow?.close();
    meetingShareRecordRemindWindow = undefined;
    mainWindow?.webContents.send('setLiving', false);
    //通知会议页面进入了会议
    mainWindow?.webContents.send('changMyselfMeetingStatus', false);
  });

  meetWindow!.on('move', () => {
    shareOperationBarWindow?.setIgnoreMouseEvents(false);
    whiteboardWindow?.setIgnoreMouseEvents(false);
    meetingShareRecordRemindWindow?.setIgnoreMouseEvents(false);
    //通知会议页面进入了会议
    mainWindow?.webContents.send('changMyselfMeetingStatus', false);
  });

  meetWindow!.on('moved', () => {
    if (shareIgnore) {
      shareOperationBarWindow?.setIgnoreMouseEvents(true, {
        forward: true,
      });
    }
    if (whiteboardIgnore) {
      whiteboardWindow?.setIgnoreMouseEvents(true, {
        forward: true,
      });
    }
  });

  meetWindow!.webContents.ipc.on(
    'set-volumeClick-events',
    async (event, volumeFlag: boolean) => {
      console.log('setVolumeClickEvents1', volumeFlag);
      shareOperationBarWindow!.webContents.send(
        'setVolumeClickEvents',
        volumeFlag,
      );
    },
  );
  meetWindow!.webContents.ipc.on(
    'set-cameraClick-events',
    async (event, volumeFlag: boolean) => {
      shareOperationBarWindow!.webContents.send(
        'setCameraClickEvents',
        volumeFlag,
      );
    },
  );
  meetWindow!.webContents.ipc.on(
    'set-recordClick-events',
    async (event, recordFlag: boolean) => {
      if (shareOperationBarWindow != undefined) {
        shareOperationBarWindow!.webContents.send(
          'setRecordClickEvents',
          recordFlag,
        );
      }
    },
  );

  //通知会议页面进入了会议
  mainWindow?.webContents.send('changMyselfMeetingStatus', true);
});

ipcMain.on('previewVideo', (_, videoUrl, fileName) => {
  // console.log(videoUrl);
  if (videoWindow == null) {
    videoWindow = new BrowserWindow({
      title: `预览：${fileName}`,
      minWidth: 1200,
      minHeight: 650,
      width: 1200,
      height: 650,
      useContentSize: true,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
      },
    });
    videoWindow.on('closed', () => {
      videoWindow = undefined;
    });
  }

  videoWindow.setMenu(null);
  if (isDevelopment) {
    videoWindow.loadURL(
      `http://localhost:8888/EasyPlayer.html?videoUrl=${videoUrl}&fileName=${fileName}`,
    );
  } else {
    videoWindow.loadURL(
      `app://./EasyPlayer.html?videoUrl=${videoUrl}&fileName=${fileName}`,
    );
  }
});

const initWebSocket = async (serverIp: string, message: {}) => {
  console.log('serverIp:', serverIp);
  webSocketClient = new WebSocket(
    `ws://` + serverIp + `:9999/VideoMeeting/WebSocket`,
  );

  webSocketClient!.onopen = () => {
    console.log('WebSocket连接已建立');
    webSocketClient!.send(JSON.stringify(message));
    console.log('登录已发送WebSocket消息:', message);
  };

  webSocketClient!.on('message', async (data: any) => {
    console.log('WebSocket收到回复：', data.toString());
    const message = JSON.parse(data.toString());
    if (message.messageType === 'share') {
      const result = {
        messageType: message.messageType,
        app: message.app,
        stream: message.stream,
        userId: message.userId,
      };
      console.log('-------------------shareVideo', result);
      meetWindow?.webContents.send('shareVideo', result);
    } else if (message.messageType === 'chatInput') {
      const result = {
        chatMessage: message.chatMessage,
        userId: message.userId,
        userName: message.userName,
        messageType: message.messageType,
        createTime: message.createTime,
      };
      meetWindow?.webContents.send('chatMessage', result);
    } else if (message.messageType === 'getInviteUser') {
      const result = {
        messageType: message.messageType,
        inviteUserList: message.inviteUserList,
      };
      meetWindow?.webContents.send('getInviteUser', result);
    } else if (message.messageType === 'inviteUser') {
      const result = {
        messageType: message.messageType,
        avatar: message.avatar,
        userName: message.userName,
        meetingCode: message.meetingCode,
        meetingName: message.meetingName,
      };
      await createInviteUserWindow(result);
    } else if (message.messageType === 'forceOut') {
      const result = {
        userId: message.userId,
        userName: message.userName,
      };
      mainWindow?.webContents.send('forceOut', result);
    } else if (message.messageType === 'getAttendedUser') {
      const result = {
        inviteUserList: message.inviteUserList,
        messageType: message.messageType,
      };
      meetWindow?.webContents.send('getAttendedList', result);
    } else if (message.messageType === 'getAppAndStream') {
      const result = {
        messageType: message.messageType,
        app: message.app,
        stream: message.stream,
      };
      meetWindow?.webContents.send('getAppAndStream', result);
    } else if (message.messageType === 'updateVideoStatus') {
      const result = {
        messageType: message.messageType,
        app: message.app,
        stream: message.stream,
        videoFlag: message.videoFlag,
      };
      meetWindow?.webContents.send('updateVideoStatus', result);
    } else if (message.messageType === 'updateAudioStatus') {
      const result = {
        messageType: message.messageType,
        app: message.app,
        stream: message.stream,
        audioFlag: message.audioFlag,
      };
      meetWindow?.webContents.send('updateAudioStatus', result);
    } else if (message.messageType === 'pull') {
      const result = {
        messageType: message.messageType,
        userId: message.userId,
        userName: message.userName,
        app: message.app,
        stream: message.stream,
        avatar: message.avatar,
        meetingCode: message.meetingCode,
      };
      meetWindow?.webContents.send('pullReceive', result);
    } else if (message.messageType === 'pullRemove') {
      const result = {
        messageType: message.messageType,
        userId: message.userId,
        meetingCode: message.meetingCode,
      };
      meetWindow?.webContents.send('pullRemove', result);
    } else if (message.messageType === 'stopControlRecord') {
      mainWindow?.webContents.send('stopControlRecord', message.data);
    } else if (message.messageType === 'closeWindow') {
      const result = {
        messageType: message.messageType,
        userId: message.userId,
        meetingCode: message.meetingCode,
      };
      meetWindow?.webContents.send('closeWindow', result);
    } else if (message.messageType === 'changeEmcee') {
      const result = {
        messageType: message.messageType,
        userId: message.userId,
        userName: message.userName,
        meetingCode: message.meetingCode,
        app: message.app,
        stream: message.stream,
        pushFlag: message.pushFlag,
      };
      meetWindow?.webContents.send('changeEmcee', result);
    } else if (message.messageType === 'meetingRemind') {
      const result = {
        messageType: message.messageType,
        userId: message.userId,
        meetingCode: message.meetingCode,
        meetingName: message.meetingName,
        appointStartTime: message.appointStartTime,
        userName: message.userName,
        avatar: message.avatar,
        leadTime: message.leadTime,
        isCreateUser: message.isCreateUser,
      };
      await createMeetingRemindWindow(result);
      meetingRemindWindow!.webContents.send('meetingRemind', result);
    } else if (message.messageType === 'stopShare') {
      const result = {
        messageType: message.messageType,
        app: message.app,
        stream: message.stream,
      };
      meetWindow?.webContents.send('stopShareReceive', result);
    } else if (message.messageType === 'changeVolume') {
      meetWindow?.webContents.send('changeVolume', message.audioFlag);
    } else if (message.messageType === 'changeVideo') {
      meetWindow?.webContents.send('changeVideo', message.videoFlag);
    } else if (message.messageType === 'compereMeetingShareRecord') {
      const result = {
        messageType: message.messageType,
        userId: message.userId,
        userName: message.userName,
        pushFlag: message.pushFlag,
        pullFlag: message.pullFlag,
        isRecordFlag: message.isRecordFlag,
      };
      await createMeetingShareRecordRemindWindow(result);
    } else if (message.messageType === 'meetingShareRecord') {
      meetWindow?.webContents.send('changeRecord', message.isRecordFlag);
    } else if (message.messageType === 'getMyselfMeetingInfo') {
      mainWindow?.webContents.send(
        'changMyselfMeetingStatus',
        message.pushFlag,
      );
    }
  });

  webSocketClient!.onclose = () => {
    console.log('WebSocket连接已关闭');
  };

  webSocketClient!.onerror = (error: any) => {
    console.error('WebSocket错误：' + error.error);
  };
};

async function createInviteUserWindow(result: {
  messageType: string;
  avatar: string;
  userName: string;
  meetingCode: string;
  meetingName: string;
}) {
  if (inviteUserWindow === undefined) {
    const { workArea, workAreaSize } = screen.getPrimaryDisplay();
    inviteUserWindow = new BrowserWindow({
      width: 400,
      height: 200,
      x: workArea.width - 430,
      y: workArea.height - 230,
      frame: false,
      resizable: false,
      minimizable: false,
      maximizable: false,
      skipTaskbar: true,
      useContentSize: true,
      transparent: true,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    inviteUserWindow.on('closed', () => {
      inviteUserWindow = undefined;
    });
    inviteUserWindow.setMenu(null);
    if (isDevelopment) {
      await inviteUserWindow.loadURL(
        `http://localhost:8888/#/inviteUser?inviteUserData=` +
          JSON.stringify(result),
      );
    } else {
      await inviteUserWindow.loadURL(
        `app://./index.html/#/inviteUser?inviteUserData=` +
          JSON.stringify(result),
      );
    }
    inviteUserWindow.setAlwaysOnTop(true);
    inviteUserWindow.setOpacity(0.8);
    inviteUserWindow.webContents.openDevTools();

    inviteUserWindow.webContents.ipc.on('close-inviteUser', async (event) => {
      inviteUserWindow?.close();
      inviteUserWindow = undefined;
    });
  }
}

async function createShareOperationBarWindow(
  volumeList: [],
  cameraList: [],
  volumeFlag: boolean,
  cameraFlag: boolean,
  meetingCode: string,
) {
  if (shareOperationBarWindow === undefined) {
    const { workArea, workAreaSize } = screen.getPrimaryDisplay();
    shareOperationBarWindow = new BrowserWindow({
      width: 950,
      height: 270,
      x: (workArea.width - 950) / 2,
      y: 0,
      frame: false,
      resizable: false,
      minimizable: false,
      maximizable: false,
      //skipTaskbar: true,
      useContentSize: true,
      transparent: true,
      show: false,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    shareOperationBarWindow.on('closed', () => {
      shareOperationBarWindow = undefined;
    });
    shareOperationBarWindow.setMenu(null);
    if (isDevelopment) {
      console.log('-------------cameraFlag:', cameraFlag);
      await shareOperationBarWindow.loadURL(
        `http://localhost:8888/#/shareOperationBar?volumeList=` +
          volumeList +
          '&volumeFlag=' +
          volumeFlag +
          '&cameraList=' +
          cameraList +
          '&cameraFlag=' +
          cameraFlag +
          '&meetingCode=' +
          meetingCode,
      );
    } else {
      await shareOperationBarWindow.loadURL(
        `app://./index.html/#/shareOperationBar?volumeList=` +
          volumeList +
          '&volumeFlag=' +
          volumeFlag +
          '&cameraList=' +
          cameraList +
          '&cameraFlag=' +
          cameraFlag +
          '&meetingCode=' +
          meetingCode,
      );
    }
    shareOperationBarWindow.setAlwaysOnTop(true);
    shareOperationBarWindow.webContents.openDevTools();
  }
  shareOperationBarWindow!.webContents.ipc.on(
    'set-shareOperationBarWindow-show',
    () => {
      shareOperationBarWindow!.show();
      shareOperationBarWindow!.setIgnoreMouseEvents(true, {
        forward: true,
      });
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-ignore-mouse-events',
    async (event, ignore, options) => {
      console.log('--------------------ignore:', ignore);
      const win = BrowserWindow.fromWebContents(event.sender);
      shareIgnore = ignore;
      win!.setIgnoreMouseEvents(ignore, options);
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'open-whiteboard-events',
    async (event) => {
      await openWhiteboardWindow();
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'close-shareOperationBarWindow',
    async (event) => {
      meetWindow?.webContents.send('stopShare');
      whiteboardWindow?.webContents.send('stopWhiteboardOperationBar');
      shareOperationBarWindow!.close();
      whiteboardWindow?.close();
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-toggle-events',
    async (event, audioKey: string, videoKey: string, type: string) => {
      const result = {
        audioKey: audioKey,
        videoKey: videoKey,
        type: type,
      };
      meetWindow!.webContents.send('setToggleEvents', result);
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-volumeClick-events',
    async (event, volumeFlag: boolean) => {
      meetWindow!.webContents.send('setVolumeClickEvents', volumeFlag);
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-cameraClick-events',
    async (event, volumeFlag: boolean) => {
      meetWindow!.webContents.send('setCameraClickEvents', volumeFlag);
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-chatShow-events',
    async (event) => {
      meetWindow!.webContents.send('setChatShowEvents');
      meetWindow!.restore();
      meetWindow!.focus();
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-inviteUserShow-events',
    async (event) => {
      meetWindow!.webContents.send('setInviteUserShowEvents');
      meetWindow!.restore();
      meetWindow!.focus();
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'meeting-share-record-events',
    async (event, recordFlag: boolean) => {
      meetWindow!.webContents.send('meetingShareRecordEvents', recordFlag);
    },
  );

  shareOperationBarWindow?.webContents.ipc.on(
    'send-websocket-message',
    (event, message) => {
      if (webSocketClient) {
        webSocketClient.send(message);
        console.log('shareOperationBarWindow窗口已发送WebSocket消息:', message);
      }
    },
  );
  shareOperationBarWindow!.webContents.ipc.on(
    'set-recordClick-events',
    async (event, recordFlag: boolean) => {
      console.log('--------------------setRecordClickEvents:', recordFlag);
      meetWindow!.webContents.send('setRecordClickEvents', recordFlag);
    },
  );
}

async function openWhiteboardWindow() {
  const { workArea, workAreaSize } = screen.getPrimaryDisplay();
  if (whiteboardWindow === undefined) {
    whiteboardWindow = new BrowserWindow({
      frame: false,
      resizable: false,
      minimizable: false,
      maximizable: false,
      width: workArea.width,
      height: workArea.height,
      //skipTaskbar: true,
      useContentSize: true,
      transparent: true,
      show: false,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    whiteboardWindow.on('closed', () => {
      whiteboardWindow = undefined;
    });
    whiteboardWindow.setMenu(null);
    if (isDevelopment) {
      await whiteboardWindow.loadURL(
        `http://localhost:8888/#/whiteboardOperationBar`,
      );
    } else {
      await whiteboardWindow.loadURL(
        `app://./index.html/#/whiteboardOperationBar`,
      );
    }
    whiteboardWindow.setAlwaysOnTop(true);
    whiteboardWindow.webContents.openDevTools();
  }
  whiteboardWindow?.webContents.ipc.on('set-whiteboardWindow-show', () => {
    whiteboardWindow!.show();
  });

  whiteboardWindow!.webContents.ipc.on(
    'set-whiteboard-ignore-mouse-events',
    async (event, ignore, options) => {
      const win = BrowserWindow.fromWebContents(event.sender);
      whiteboardIgnore = ignore;
      win!.setIgnoreMouseEvents(ignore, options);
    },
  );

  whiteboardWindow!.webContents.ipc.on('capture-screen', async (event) => {
    const sources = await desktopCapturer.getSources({
      types: ['screen'],
      thumbnailSize: { width: workArea.width, height: workArea.height },
    });
    for (const source of sources) {
      if (source.name === '整个屏幕') {
        const image = nativeImage.createFromDataURL(
          source.thumbnail.toDataURL(),
        );
        // 获取文档目录路径
        let documentsPath = app.getPath('documents');
        // 创建一个 Date 对象，它将包含当前的日期和时间
        const currentDate = new Date();
        // 获取年、月、日
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth() + 1; // 月份是从 0 开始计数的，所以要加 1
        const day = currentDate.getDate();
        const hours = String(currentDate.getHours()).padStart(2, '0');
        const minutes = String(currentDate.getMinutes()).padStart(2, '0');
        const seconds = String(currentDate.getSeconds()).padStart(2, '0');
        console.log(
          `当前时间：${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
        );
        const fillName =
          year.toString() +
          month.toString() +
          day.toString() +
          '-' +
          hours +
          minutes +
          seconds +
          '_';
        documentsPath = documentsPath + '/teachManager/' + fillName;
        // 使用 fs.mkdir 创建文件夹
        fs.mkdir(documentsPath, { recursive: true }, (err: Error) => {
          if (err) {
            console.error('Error creating folder:', err);
          } else {
            console.log('Folder created successfully.');
            const filePath = path.join(documentsPath, fillName + '.png');
            // 将 Buffer 写入文件
            fs.writeFileSync(filePath, image.toPNG());
            shell.showItemInFolder(
              path.resolve(documentsPath + '/' + fillName + '.png'),
            );
          }
        });
      }
    }
  });

  whiteboardWindow!.webContents.ipc.on(
    'close-whiteboardWindow',
    async (event) => {
      whiteboardWindow!.close();
      whiteboardWindow = undefined;
    },
  );
  //监听聚焦事件，取消聚焦
  whiteboardWindow!.on('focus', () => {
    whiteboardWindow!.blur();
  });
}

//创建一个提醒弹框
async function createMeetingRemindWindow(result: {
  messageType: string;
  userId: string;
  meetingCode: string;
  meetingName: string;
  appointStartTime: string;
  userName: string;
  avatar: string;
  leadTime: string;
  isCreateUser: boolean;
}) {
  if (meetingRemindWindow === undefined) {
    const { workArea, workAreaSize } = screen.getPrimaryDisplay();
    meetingRemindWindow = new BrowserWindow({
      width: 400,
      height: 200,
      x: workArea.width - 430,
      y: workArea.height - 230,
      frame: false,
      resizable: false,
      minimizable: false,
      maximizable: false,
      skipTaskbar: true,
      useContentSize: true,
      transparent: true,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    meetingRemindWindow.on('closed', () => {
      meetingRemindWindow = undefined;
    });
    meetingRemindWindow.setMenu(null);
    if (isDevelopment) {
      await meetingRemindWindow.loadURL(
        `http://localhost:8888/#/meetingRemind?meetingRemindData=` +
          JSON.stringify(result),
      );
    } else {
      await meetingRemindWindow.loadURL(
        `app://./index.html/#/meetingRemind?meetingRemindData=` +
          JSON.stringify(result),
      );
    }
    meetingRemindWindow.setAlwaysOnTop(true);
    meetingRemindWindow.setOpacity(0.8);
    meetingRemindWindow.webContents.openDevTools();

    meetingRemindWindow.webContents.ipc.on(
      'close-meetingRemind',
      async (event) => {
        meetingRemindWindow?.close();
        meetingRemindWindow = undefined;
      },
    );
  }
}

//创建一个会议录制提醒弹框
async function createMeetingShareRecordRemindWindow(result: {
  messageType: string;
  userId: string;
  userName: string;
  pushFlag: boolean;
  pullFlag: boolean;
  isRecordFlag: boolean;
}) {
  if (meetingShareRecordRemindWindow === undefined) {
    const { workArea, workAreaSize } = screen.getPrimaryDisplay();
    meetingShareRecordRemindWindow = new BrowserWindow({
      width: 400,
      height: 200,
      frame: false,
      resizable: false,
      minimizable: false,
      maximizable: false,
      skipTaskbar: true,
      useContentSize: true,
      transparent: true,
      webPreferences: {
        contextIsolation: true,
        preload: path.join(__dirname, 'preload.js'),
        webSecurity: false,
        webviewTag: true,
      },
    });
    meetingShareRecordRemindWindow.on('closed', () => {
      meetingShareRecordRemindWindow = undefined;
    });
    meetingShareRecordRemindWindow.setMenu(null);
    if (isDevelopment) {
      await meetingShareRecordRemindWindow.loadURL(
        `http://localhost:8888/#/meetingShareRecordRemind?meetingRemindData=` +
          JSON.stringify(result),
      );
    } else {
      await meetingShareRecordRemindWindow.loadURL(
        `app://./index.html/#/meetingShareRecordRemind?meetingRemindData=` +
          JSON.stringify(result),
      );
    }
    meetingShareRecordRemindWindow.setAlwaysOnTop(true);
    meetingShareRecordRemindWindow.setOpacity(0.8);
    meetingShareRecordRemindWindow.webContents.openDevTools();

    meetingShareRecordRemindWindow.webContents.ipc.on(
      'closeMeetingShareRecordRemind',
      async (event) => {
        meetingShareRecordRemindWindow?.close();
        meetingShareRecordRemindWindow = undefined;
      },
    );

    meetingShareRecordRemindWindow!.webContents.ipc.on(
      'record-notice-to-leave-meeting',
      () => {
        meetWindow!.webContents.send('recordNoticeToLeaveMeeting');
      },
    );

    meetingShareRecordRemindWindow!.webContents.ipc.on(
      'start_record-meeting',
      () => {
        meetWindow!.webContents.send('startRecordMeeting');
      },
    );
    meetingShareRecordRemindWindow!.webContents.ipc.on(
      'set-recordClick-events',
      async (event, recordFlag: boolean) => {
        meetWindow!.webContents.send('setRecordClickEvents', recordFlag);
        if (shareOperationBarWindow !== undefined) {
          shareOperationBarWindow!.webContents.send(
            'setRecordClickEvents',
            recordFlag,
          );
        }
      },
    );
  }
}
